package com.sitanyun.merchant.guide.frament.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.NumberKeyListener;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.AccountBean;
import com.sitanyun.merchant.guide.bean.RealNameBean;
import com.sitanyun.merchant.guide.bean.RealnameInfoBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.RealNameAPresenterImpl;
import com.sitanyun.merchant.guide.frament.presenter.inter.IRealNameAPresenter;
import com.sitanyun.merchant.guide.frament.view.inter.IRealNameAView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.activity.AgreementActivity;
import com.sitanyun.merchant.guide.weiht.IdentityUtils;
import com.sitanyun.merchant.guide.weiht.Loading_view;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceReal;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.sitanyun.merchant.guide.weiht.StringReplaceUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 实名认证
 */
public class RealNameActivity extends BaseActivity implements IRealNameAView {


    @BindView(R.id.id_ll)
    LinearLayout idLl;
    @BindView(R.id.cb_protocol)
    CheckBox cbProtocol;
    @BindView(R.id.cb_text)
    TextView cbText;
    @BindView(R.id.realname_sbm)
    TextView realnameSbm;
    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.realname)
    EditText realname;
    @BindView(R.id.realsfz)
    EditText realsfz;
    @BindView(R.id.realname_save)
    TextView realnameSave;
    @BindView(R.id.sfzsc)
    TextView sfzsc;
    @BindView(R.id.smrz_msg)
    TextView smrzMsg;
    @BindView(R.id.ty_xy)
    LinearLayout tyXy;
    private IRealNameAPresenter mIRealNameAPresenter;
    private String fileid = "";
    private String fileids = "";
    private String data;
    private String account;
    private String name;
    private String picfont = "";
    private String picback = "";
    private String namesx;
    private String filepath = "";
    private String filepath2 = "";
    private Loading_view loading_view;

    @Override
    public int getLayoutId() {
        return R.layout.activity_real_name;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("实名认证");
        loading_view = new Loading_view(RealNameActivity.this, R.style.CustomDialog);
        realname.setText(getIntent().getStringExtra("name"));
        name = getIntent().getStringExtra("name");
        String isIndividual = getIntent().getStringExtra("isIndividual");
        //已实名认证
        if (isIndividual.equals("1")) {
            smrzMsg.setText("您已完成实名认证");
            sfzsc.setText("已完成");
            sfzsc.setTextColor(getResources().getColor(R.color.shop));
            cbProtocol.setChecked(true);
            OkHttpUtils.get().url(Urls.interestinfo)
                    .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                    .addHeader("Content-Type", "application/json").build().execute(new StringCallbacks() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {
                    RealnameInfoBean realnameInfoBean = new Gson().fromJson(response, RealnameInfoBean.class);
                    picfont = realnameInfoBean.getData().getIdPicFrontUrl() + "";
                    picback = realnameInfoBean.getData().getIdPicBackUrl() + "";
                    fileid = realnameInfoBean.getData().getIdPicFront() + "";
                    fileids = realnameInfoBean.getData().getIdPicBack() + "";
                    realname.setText(realnameInfoBean.getData().getName());
                    realsfz.setText(StringReplaceUtil.bankCardReplaceWithStar(realnameInfoBean.getData().getIdNum() + ""));
                    //不可点击
                    realname.setEnabled(false);
                    realsfz.setEnabled(false);

                }
            });
            idLl.setEnabled(false);
            tyXy.setVisibility(View.GONE);
            realnameSbm.setVisibility(View.GONE);
            realnameSave.setVisibility(View.GONE);
        } else {
            idLl.setEnabled(true);
            tyXy.setVisibility(View.VISIBLE);
            realnameSbm.setVisibility(View.VISIBLE);
            realnameSave.setVisibility(View.VISIBLE);
            //未实名认证
            if (!SharedPreferenceReal.getStringData("realname").isEmpty()) {
                realname.setText(SharedPreferenceReal.getStringData("realname"));
            }
            if (!SharedPreferenceReal.getStringData("realsfz").isEmpty()) {
                realsfz.setText(SharedPreferenceReal.getStringData("realsfz"));
            }
            if (!SharedPreferenceReal.getStringData("filepath").isEmpty()) {
                filepath = SharedPreferenceReal.getStringData("filepath");
            }
            if (!SharedPreferenceReal.getStringData("filepath2").isEmpty()) {
                filepath2 = SharedPreferenceReal.getStringData("filepath2");
            }
            if (!SharedPreferenceReal.getStringData("fileid").isEmpty()) {
                fileid = SharedPreferenceReal.getStringData("fileid");
            }
            if (!SharedPreferenceReal.getStringData("fileids").isEmpty()) {
                fileids = SharedPreferenceReal.getStringData("fileids");
            }
            if (!fileid.isEmpty() || !fileids.isEmpty()) {
                sfzsc.setText("已完成");
            }
        }


        realsfz.setKeyListener(new NumberKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_CLASS_PHONE;
            }

            @Override
            protected char[] getAcceptedChars() {
                return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'X'};
            }
        });

    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIRealNameAPresenter = new RealNameAPresenterImpl(this);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.cb_text, R.id.id_ll, R.id.realname_sbm, R.id.realname_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_text:
                startActivity(new Intent(RealNameActivity.this, AgreementActivity.class).putExtra("weburl", "3"));
                break;

            case R.id.id_ll:
                Intent intent = new Intent(RealNameActivity.this, RealIDActivity.class);
                // startActivity(intent);
                if (realname.getText().toString().length() == 1) {
                    ToastUtil.showToast(RealNameActivity.this, "请输入正确名字");
                    return;
                }
                intent.putExtra("names", realname.getText().toString().trim());
                intent.putExtra("isIndividuals", getIntent().getStringExtra("isIndividual"));
//                if (!filepath.isEmpty()){
//                    intent.putExtra("filepath",filepath+"");
//                }
//                if (!filepath2.isEmpty()){
//                    intent.putExtra("filepath2",filepath2+"");
//                }

                if (!fileid.isEmpty()) {
                    intent.putExtra("fileid", fileid);
                    intent.putExtra("picid", picfont);
                }
                if (!fileids.isEmpty()) {
                    intent.putExtra("fileids", fileids);
                    intent.putExtra("picbackid", picback);
                }
                startActivityForResult(intent, 2);// 请求码
                //  startActivity(new Intent(RealNameActivity.this, RealIDActivity.class));
                break;
            case R.id.realname_sbm:
                if (realsfz.getText().toString().isEmpty()) {
                    ToastUtil.showToast(RealNameActivity.this, "请输入身份证号");
                    return;
                }
                if (!IdentityUtils.validate_effective(realsfz.getText().toString())) {
                    ToastUtil.showToast(RealNameActivity.this, "请输入正确身份证号");
                    return;
                }
                if (fileid.isEmpty()) {
                    ToastUtil.showToast(RealNameActivity.this, "请上传身份证正面");
                    return;
                }
                if (fileids.isEmpty()) {
                    ToastUtil.showToast(RealNameActivity.this, "请上传身份证反面");
                    return;
                }
                if (!cbProtocol.isChecked()) {
                    ToastUtil.showToast(RealNameActivity.this, "请同意《电子签约服务协议》");
                    return;
                }
                loading_view.show();
                mIRealNameAPresenter.setrealname(SharedPreferenceUtil.getStringData("staffid"), realname.getText().toString().trim(),
                        realsfz.getText().toString().trim(), fileid, fileids);


                break;
        }
    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    /**
     * 存完信息
     * @param response
     * @param responseFlag
     * @param <T>
     */
    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IRealNameAView.RESPONSE_ONE) {
            RealNameBean swishShopBean = (RealNameBean) response;
            loading_view.dismiss();
            if (swishShopBean.getCode() == 0) {
                data = swishShopBean.getData();
                SharedPreferenceUtil.SaveData("individ", data + "");
                loading_view.show();
                mIRealNameAPresenter.getaccountIdentity(data, realname.getText().toString().trim(), realsfz.getText().toString().trim());

            } else {
                startActivity(new Intent(RealNameActivity.this, SuccesRealActivity.class).putExtra("type", "2")
                        .putExtra("shibai", swishShopBean.getMsg() + "")
                        .putExtra("name",realname.getText().toString().trim())
                        .putExtra("idNum",realsfz.getText().toString().trim())
                        .putExtra("idPicFront",fileid)
                        .putExtra("idPicBack",fileids)
                );
            }
        }
    }

    //签约帐号
    @Override
    public <T> void responseaccountIdentity(T response, int responseFlag) {
        if (responseFlag == IRealNameAView.RESPONSE_ONE) {
            AccountBean accountBean = (AccountBean) response;
            loading_view.dismiss();
            if (accountBean.getCode() == 0) {
                account = accountBean.getData();
                mIRealNameAPresenter.getuserSign(data, account);
                loading_view.show();
            } else {
                startActivity(new Intent(RealNameActivity.this, SuccesRealActivity.class).putExtra("type", "2")
                        .putExtra("shibai", accountBean.getMsg() + "")
                        .putExtra("name",realname.getText().toString().trim())
                        .putExtra("idNum",realsfz.getText().toString().trim())
                        .putExtra("idPicFront",fileid)
                        .putExtra("idPicBack",fileids));
            }
        }
    }

    //签约
    @Override
    public <T> void responseuserSign(T response, int responseFlag) {
        if (responseFlag == IRealNameAView.RESPONSE_ONE) {
            loading_view.dismiss();
            AccountBean accountBean = (AccountBean) response;
            if (accountBean.getCode() == 0) {
                startActivity(new Intent(RealNameActivity.this, SuccesRealActivity.class).putExtra("type", "1"));
                SharedPreferenceUtil.SaveData("isindividuals","1");
                finish();
            } else {
                startActivity(new Intent(RealNameActivity.this, SuccesRealActivity.class).putExtra("type", "2")
                        .putExtra("shibai", accountBean.getMsg() + "")
                        .putExtra("name",realname.getText().toString().trim())
                        .putExtra("idNum",realsfz.getText().toString().trim())
                        .putExtra("idPicFront",fileid)
                        .putExtra("idPicBack",fileids));

            }
        }
    }

    //保存
    @OnClick(R.id.realname_save)
    public void onViewClicked() {

        if (!realname.getText().toString().isEmpty()) {
            SharedPreferenceReal.SaveData("realname", realname.getText().toString().trim());

        }

        if (!realsfz.getText().toString().isEmpty()) {
            SharedPreferenceReal.SaveData("realsfz", realsfz.getText().toString().trim());

        }
        if (!filepath.isEmpty()) {
            SharedPreferenceReal.SaveData("filepath", filepath);

        }
        if (!filepath2.isEmpty()) {
            SharedPreferenceReal.SaveData("filepath2", filepath2);

        }
        if (!fileid.isEmpty()) {
            SharedPreferenceReal.SaveData("fileid", fileid);

        }
        if (!fileids.isEmpty()) {
            SharedPreferenceReal.SaveData("fileids", fileids);

        }
        SharedPreferenceUtil.SaveData("sfz", realsfz.getText().toString());
        finish();

        ToastUtil.showToast(RealNameActivity.this, "保存成功");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == 2) {// 然后把返回的数据放到对应的EditText中
                fileid = data.getStringExtra("fileid");
                fileids = data.getStringExtra("fileids");
                filepath = data.getStringExtra("filepath");
                filepath2 = data.getStringExtra("filepath2");
                if (!fileid.isEmpty() || !fileids.isEmpty()) {
                    sfzsc.setText("已完成");
                }
            }
        }

    }

}
